#include "Creature.h"
#include "base/core/lua_head.h"
#include "Common/Lib/ScriptSafeCall.h"
#include "Script/ScriptMgr.h"

using namespace luabridge;

bool Creature::RegistLuaClass(lua_State* state)
{
	getGlobalNamespace(state)
		.beginNamespace("_G")
		.beginClass<Creature>("LuaCreature")

		.addFunction("IsDead", &Creature::LuaIsDead)
		.addFunction("GetAttr", &Creature::GetAttr)

		.endClass()
		.endNamespace();
	return true;
}

int Creature::LuaIsDead()
{
	bool result = IsDead();
	return result ? 1 : 0;
}

int Creature::DoSkillString(uint32_t skillId,		// 技能id
							uint32_t skillLevel,	// 技能等级
							const char* luaString,	// 需要执行的字符串
							CharIDType casterId,	// 技能释放者
							CharIDType targetId,	// 技能目标
							uint32_t chargeTime		// 技能蓄力时间
							)
{
	bool retCode = false;
	int index = 0;
	LuaScript* script = g_GetScriptMgr()->GetScript();
	MMOLOG_ASSERT(script != nullptr);

	if (strcmp(luaString, "") == 0)
	{
		return 0;
	}
	else
	{
		LuaRef refRet(script->GetState());
		ScriptSafeCall safeCall(script);
		script->PushTable();

		script->PushInt(skillId);
		script->SetTableIndex(++index);

		script->PushInt(skillLevel);
		script->SetTableIndex(++index);

		script->PushInt(chargeTime);
		script->SetTableIndex(++index);

		script->PushString(luaString);
		script->SetTableIndex(++index);

		script->PushInt((uint32_t)casterId);
		script->SetTableIndex(++index);

		script->PushInt((uint32_t)targetId);
		script->SetTableIndex(++index);

		LuaRef refTable = LuaRef::fromStack(script->GetState(), script->GetTopIndex());
		retCode = script->CallTableFuncRet("Skill", "DoSkillString", refRet, refTable);
		MMO_ASSERT(retCode && refRet.isTable());
		return refRet[1].cast<int>();
	}
}